<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>任务树形表格</title>
    <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/icon.css">
    <script type="text/javascript" src="https://www.jeasyui.com/easyui/jquery.min.js"></script>
    <script type="text/javascript" src="https://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/luxon@1.27.0/build/global/luxon.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }

        #treeTable {
            width: 100%;
            max-width: 800px;
        }
    </style>
</head>

<body>
    <h2>任务树形表格</h2>
    <table id="treeTable" class="easyui-treegrid" title="任务列表" style="width:100%;height:auto" data-options="
            method: 'get',
            idField: 'id',
            treeField: 'name',
            fitColumns: true,
            singleSelect: true,
            toolbar: '#toolbar'
        ">
        <thead>
            <tr>
                <th data-options="field:'name',width:200">任务名称</th>
                <th data-options="field:'start',width:150,align:'center'">开始时间</th>
                <th data-options="field:'finish',width:150,align:'center'">结束时间</th>
                <th data-options="field:'duration',width:150,align:'center'">持续时间</th>
            </tr>
        </thead>
    </table>

    <div id="toolbar" style="padding:5px;">
        <input type="file" id="xmlFile" accept=".xml" onchange="loadXMLFile(this)" style="display:none;" />
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="triggerFileUpload()">上传 XML 文件</a>
    </div>

    <script>
        // 触发文件上传
        function triggerFileUpload() {
            document.getElementById('xmlFile').click();
        }

        // 读取上传的 XML 文件并加载到树形表格
        function loadXMLFile(input) {
            const file = input.files[0];

            if (!file) {
                alert('请选择一个 XML 文件');
                return;
            }

            const reader = new FileReader();
            reader.onload = function (event) {
                const xmlText = event.target.result;
                const treeData = parseXMLToTreeData(xmlText);
                $('#treeTable').treegrid('loadData', treeData);
            };

            reader.readAsText(file);
        }

        // 解析 XML 文件并转换为 EasyUI 树形表格数据
        function parseXMLToTreeData(xmlText) {
            const parser = new DOMParser();
            const xmlDoc = parser.parseFromString(xmlText, 'application/xml');

            const tasks = [];
            const taskNodes = xmlDoc.getElementsByTagName('Task');

            // 安全解析函数
            const getChildText = (node, tagName) => {
                const elements = node.getElementsByTagName(tagName);
                return elements.length > 0 ? elements[0].textContent : '';
            };

            for (let i = 0; i < taskNodes.length; i++) {
                const taskNode = taskNodes[i];
                const task = {
                    id: getChildText(taskNode, 'ID'),
                    name: getChildText(taskNode, 'Name'),
                    start: getChildText(taskNode, 'Start'),
                    finish: getChildText(taskNode, 'Finish'),
                    outlineLevel: parseInt(getChildText(taskNode, 'OutlineLevel')) || 1,
                    duration: getChildText(taskNode, 'Duration'),
                    children: []
                };
                tasks.push(task);
            }
            // 转换持续时间为“天 小时”格式
            tasks.forEach(task => {
                task.duration = convertDuration(task.duration);
            });

            // 构建树形结构
            const treeData = [];
            const stack = [];

            tasks.forEach(task => {
                while (stack.length > 0 && stack[stack.length - 1].outlineLevel >= task.outlineLevel) {
                    stack.pop();
                }

                if (stack.length === 0) {
                    treeData.push(task);
                } else {
                    stack[stack.length - 1].children.push(task);
                }

                stack.push(task);
            });

            // 去掉 treeData 的第一个元素
            if (treeData.length > 0) {
                treeData.shift();
            }

            

            return treeData;
        }

        // 将 ISO 8601 格式的持续时间转换为“天 小时”格式
        function convertDuration(duration) {
            if (!duration) return '';

            const durationRegex = /PT(\d+)H(\d+)M(\d+)S/;
            const match = duration.match(durationRegex);

            if (!match) return '';

            const hours = parseInt(match[1], 10);
            const days = Math.floor(hours / 24);
            const remainingHours = hours % 24;

            if (days > 0) {
                return `${days}天 ${remainingHours}小时`;
            } else {
                return `${remainingHours}小时`;
            }
        }

        $(document).ready(function () {
            // 初始化树形表格为空
            $('#treeTable').treegrid('loadData', []);
        });
    </script>
</body>

</html>